package com.imooc.ecommerce.config;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.lang.reflect.Method;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author Yaxi.Zhang
 * @since 2022/11/12 16:46
 */
@Slf4j
public class AsyncPoolConfig implements AsyncConfigurer {

    private static final int coreSize = Runtime.getRuntime().availableProcessors();

    /**
     * <p>将自定义的线程池注入到 Spring 容器中
     */
    @Bean
    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();

        executor.setCorePoolSize(coreSize + 1);
        executor.setMaxPoolSize(coreSize << 1);
        executor.setQueueCapacity(20);
        executor.setKeepAliveSeconds(60);
        // 这个非常重要, 打印线程池名称的前缀， 用于确定使用的线程池
        executor.setThreadNamePrefix("Goods-Async-");

        // 等待所有任务结果候再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setAwaitTerminationSeconds(60);
        // 定义拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 初始化线程池, 初始化 core 线程
        executor.initialize();

        return executor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new AsyncExceptionHandler();
    }

    static class AsyncExceptionHandler implements AsyncUncaughtExceptionHandler {
        @Override
        public void handleUncaughtException(Throwable throwable, Method method,
                                            Object... objects) {
            throwable.printStackTrace();
            log.error("Async Error: [{}], Method: [{}], Param: [{}]",
                    throwable.getMessage(), method.getName(), JSON.toJSONString(objects));
            // TODO 发送邮件或者是短信, 做进一步的报警处理
        }
    }
}
